#include "../../Header/Core/StateManager.h"

StateManager* StateManager::m_Instance = 0;

StateManager::StateManager()
: m_CurrentState(0), m_PrevState(0), m_NextState(0),
m_IsDeleteOldState(false)
{
	m_StaticStateList.resize(0);
}

StateManager::~StateManager()
{
	__int32_ iCount = m_StaticStateList.size();
	for (__int32_ i = 0; i < iCount; i++)
	{
		m_StaticStateList.at(i)->Destroy();
		SAFE_DELETE(m_StaticStateList.at(i));
	}
	m_StaticStateList.clear();
}

void StateManager::AddState(State* newState)
{
	if (!newState)
	{
#if CURRENT_DBG_MODE == DBG_FUNC
		Device::GetInstance()->LogEx("StateManager state: Add null state\n");
#endif
		return;
	}
	m_StaticStateList.push_back(newState);
}

void StateManager::Update(__float_ deltaTime, __bool_ isPause)
{
	//switch if has new state
	if (m_CurrentState != m_NextState)
	{
		if (m_CurrentState)
		{
#if CURRENT_DBG_MODE == DBG_FUNC
			Device::GetInstance()->LogEx("StateManager state: Delete old state\n");
#endif
			m_CurrentState->Destroy();
		}

		if (m_IsDeleteOldState)
		{
			SAFE_DELETE(m_CurrentState);
		}
#if CURRENT_DBG_MODE == DBG_FUNC
		Device::GetInstance()->LogEx("StateManager state: Init new state\n");
#endif
		m_CurrentState = m_NextState;
		m_CurrentState->Init(); //Must be edit
	}
	//update current state
	if (m_CurrentState)
	{
		if (!isPause)
		{
			m_CurrentState->Update(deltaTime);
		}
		m_CurrentState->Draw();
	}
}

void StateManager::SwitchState(State* state)
{
	m_NextState = state;
}